package main

import (
	"flag"
	"log"
	"os"
	"os/exec"
	"syscall"

	"github.com/JackKCWong/go-cage/cage"
)


func ensureNotEUID() {
	euid := syscall.Geteuid()
	uid := syscall.Getuid()
	egid := syscall.Getegid()
	gid := syscall.Getgid()
	if uid != euid || gid != egid {
		log.Fatalf("go runtime is setuid uids:(%d vs %d), gids(%d vs %d)", uid, euid, gid, egid)
	}
	if uid == 0 {
		log.Fatalf("running as root is not advised. use capabilities instead.")
	}
}

func main() {
	ensureNotEUID()

	newUid := flag.Int("uid", -1, "new uid")
	newGid := flag.Int("gid", -1, "new gid")

	flag.Parse()
	args := flag.Args()

	if *newUid == -1 {
		flag.Usage()
		log.Fatalf("use -uid to set new user id")
	}

	if *newGid == -1 {
		flag.Usage()
		log.Fatalf("use -gid to set new group id")
	}

	if err := cage.SetIDsWithCaps(*newUid, *newGid, []int{}); err != nil {
		log.Fatalf("failed to set uid/gid: %q", err)
	}

	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		log.Fatalf("failed to exec: %q", err)
	}
}